import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Divider, Button, Form, Input, Row, Col, Select, Card, Icon, Popconfirm, message } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './style.less';
import IconFont from '../../components/Icon';

import ImportButton from './components/importButton'
import ExportButton from './components/exportButton'
import AddCompany from './components/AddCompany'


import PublicTableWrapper from '@/components/TableForm'


const selectOptions = [
    { value: '医疗设备、器械类', key: '医疗设备、器械类' },
    { value: '学校功能设备类', key: '学校功能设备类' },
    { value: '监控设备及系统类', key: '监控设备及系统类' },
    { value: '公安消防设备类', key: '公安消防设备类' },
    { value: '教育典教类', key: '教育典教类' },
    { value: '车辆交通类', key: '车辆交通类' },
    { value: '纺织类', key: '纺织类' },
    { value: '信息系统集成类', key: '信息系统集成类' },
    { value: '办公家具类', key: '办公家具类' },
    { value: '体育健身类', key: '体育健身类' },
    { value: '其他类', key: '其他类' }
]
const children = []
selectOptions.forEach(v => {
    children.push(<Select.Option value={v.key}>{v.value}</Select.Option>)
})



@connect(({ enterpriseandtable, home, user }) => ({
    enterpriseandtable,
    home,
    user
}))

// eslint-disable-next-line react/prefer-stateless-function
class Management extends Component {
    state = {
        // 搜索表展开收起
        expand: false,
        // 检查表格选择项
        selectedRowKeys: [], 

        // 表格
        tableLoading: false,
        dataSource: [],
        page: 1,
        pageSize: 10,
        search: {},
        totalCount: 1,
        columns: [
            {
                title: '企业名称',
                dataIndex: 'name',
                render: (_, record) => (
                    <a
                        onClick={() => this.toCompanyInfo(_, record)}
                        className={styles.tableListText}
                    >
                        {record.name}
                    </a>
                ),
            },
            {
                title: '所在街道',
                dataIndex: 'street',
            },
            {
                title: '行业类型',
                dataIndex: 'industry',
            },
            {
                title: '产品数量',
                dataIndex: 'numble',
            },
            {
                title: '法人代表',
                dataIndex: 'owner',
            },
            {
                title: '联系电话',
                dataIndex: 'phone',
                align: 'center',
                hideInSearch: true
            },
            {
                title: '信息完善率',
                dataIndex: 'status',
                align: 'center',
                hideInSearch: true,
                render: (_, record) => {
                    let color
                    if (record.status === 9) {
                        color = "green"
                    } else if (record.status < 3) {
                        color = "red"
                    } else {
                        color = "#1890ff"
                    }
                    return (
                        <span style={{
                            color
                        }}>{`${record.status + 1}0%`}</span>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                align: 'center',
                render: (_, record, index) => (
                <>
                    <a
                        onClick={() => this.toCompanyInfo(_, record)}
                    >制表</a>
                    <Divider type="vertical" />
                    <Popconfirm
                        title="你确定要删除吗？"
                        onConfirm={() => this.handleDelect(_, record, index)}
                        okText="是"
                        cancelText="否"
                    >
                        <a href="#">删除</a>
                    </Popconfirm>
                </>
                ),
            },
        ],
    }

    // 初始化
    componentDidMount() {
        // 获取有哪个街道的权限
        const { user } = this.props
        // 街道的权限id
        const streetid = user.streetId

        // 获取表格
        this.initfetch()
    }

    // 生成表头搜索
    getFields() {
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } }
        const { getFieldDecorator } = this.props.form
        const count = !!this.state.expand;
        if ( count ) {
            return (
                <>
                    <Col span={8}>
                        <Form.Item label="企业名称" {...formItemLayout}>
                            {getFieldDecorator("name")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="所属街道" {...formItemLayout}>
                            {getFieldDecorator("street")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="法人名称" {...formItemLayout}>
                            {getFieldDecorator("owner")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="产品名称" {...formItemLayout}>
                            {getFieldDecorator("product")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="行业类型" {...formItemLayout}>
                            {getFieldDecorator("industry")(
                                <Select placeholder="请选择">
                                    {children}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </>
            )
        }
        return (
            <>
                <Col span={8} style={{display: 'block'}}>
                    <Form.Item label="企业名称" {...formItemLayout}>
                        {getFieldDecorator("name")(<Input placeholder="请输入" />)}
                    </Form.Item>
                </Col>
                <Col span={8} style={{display: 'block'}}>
                    <Form.Item label="所属街道" {...formItemLayout}>
                        {getFieldDecorator("street")(<Input placeholder="请输入" />)}
                    </Form.Item>
                </Col>
            </>
        )
    }

    // 获取表格
    initfetch = () => {
        const { dispatch } = this.props
        const { page, pageSize, search } = this.state
        this.setState({
            tableLoading: true
        })
        dispatch({
            type: 'enterpriseandtable/fetch',
            payload: {
                limit: pageSize,
                offset: (page-1)*10,
                search
            }
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    totalCount: res.totalPageSize,
                    dataSource: res.tableListDataSource
                })
            }
            this.setState({
                tableLoading: false,
            })
        })
    }

    // 搜索表查询
    handleSearch = e => {
        const { home } = this.props
        let originallyArrary = [...home.companyInformation.tableBasicList]
        e.preventDefault()

        this.props.form.validateFields((err, values) => {
            Object.keys(values).forEach(key => {
                if (values[key]) {
                    const newBlank = []
                    // 搜索产品时在嵌套对象里搜索
                    if (key === 'product') {
                        originallyArrary.forEach((val, index) => {
                            // 记录是否含有产品
                            let isProduct = false
                            val.details_information.product.forEach(v => {
                                if (v.product.includes(values[key])) {
                                    // 防止多个产品名重复增加列表
                                    isProduct = true
                                }
                            })
                            if (isProduct) {
                                newBlank.push(originallyArrary[index])
                            }
                        })
                    } else {
                        originallyArrary.forEach((val, index) => {
                            if (val[key].includes(values[key])) {
                                newBlank.push(originallyArrary[index])
                            }
                        })
                    }
                    originallyArrary = newBlank
                }
            })
            this.setState({
                dataSource: originallyArrary
            })
        })

    }

    // 搜索表重置
    handleReset = () => {
        this.props.form.resetFields()
    }

    // 收起展开
    toggle = () => {
        const { expand } = this.state
        this.setState({ expand: !expand })
    }

    //
    toCompanyInfo = (_, record) => {
        router.push(`/information/basicList/${record.id}`)
    }

    // 删除某行
    handleDelect = (_, record) => {
        console.log(record)
        message.info('删除')
    }

    // 表格选择
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys })
    }

    // 表格清空
    onClearChange = () => {
        this.setState({ selectedRowKeys: [] })
    }

    // 导入
    importConfirm = data => {
        const { dispatch, home } = this.props
        const { dataSource } = this.state
        dispatch({
            type: 'home/importConfirm',
            payload: { data, home }
        }).then(res => {
            if (res === 200) {
                this.setState({
                    dataSource: [...data, ...dataSource],
                    selectedRowKeys: []
                })
                message.success('成功！')
            }
        })
    }

    // 换页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize
        })
        // 获取数据
        const { dispatch } = this.props
        const { search } = this.state
        this.setState({
            tableLoading: true
        })
        dispatch({
            type: 'enterpriseandtable/fetch',
            payload: {
                limit: pageSize,
                offset: (page-1)*10,
                search
            }
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    totalCount: res.totalPageSize,
                    dataSource: res.tableListDataSource
                })
            }
            this.setState({
                tableLoading: false,
            })
        })
    }

    render (){
        const { home } = this.props
        // 表格选择 rowSelection配置
        const { selectedRowKeys } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }

        const RenderToolBar = () => (
            <div className={styles.toolBarBtn}>
                <AddCompany 
                    create={this.initfetch}
                />
                <ImportButton 
                    importConfirm={this.importConfirm}
                />
                {/* <Button icon="arrow-up" type="primary" className={styles.upCompany} onClick={this.exportCompanyShow}>导出报表</Button> */}
                <ExportButton 
                    data={home.companyInformation.tableBasicList}
                    selectedRowKeys={this.state.selectedRowKeys}
                />
            </div>
        )
        
        
        return (
            <PageHeaderWrapper title="企业信息表">
                <Card className={styles.proTable} bordered={false}>
                    <Form onSubmit={this.handleSearch} style={{padding: '12px 12px'}} className={styles.tableSerech}>
                        <Row gutter={24}>
                            {this.getFields()}
                            <Col span={8}>
                                <Form.Item style={{display: 'flex', justifyContent: 'center'}}>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                    <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                        重置
                                    </Button>
                                    <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
                                        {this.state.expand ? '收起' : '展开'} <Icon type={this.state.expand ? 'up' : 'down'} />
                                    </a>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                    <RenderToolBar />
                    <div style={{margin: '0 24px',marginBottom: '16px'}}>
                        <div
                            style={{
                                backgroundColor: '#e6f7ff',
                                border: '1px solid #91d5ff',
                                display: 'flex',
                                padding: '10px 20px',
                                borderRadius: '5px',
                                width: '100%',
                                position: 'relative'
                            }}>
                                <i><IconFont type="icon-gantanhao" style={{ fontSize: '16px', marginRight: '10px'}} /></i>
                                <div style={{fontWeight: 'bold'}}>
                                    已选择<span style={{color: '#1890ff', padding: '0 5px'}}>{this.state.selectedRowKeys.length}</span>项
                                </div>
                                <a style={{fontWeight: 'bold', position: 'absolute', right: '15px'}} onClick={this.onClearChange}>
                                    清空
                                </a>
                        </div>
                    </div>
                    
                    
                    <PublicTableWrapper
                        loading={this.state.tableLoading}
                        columns={this.state.columns}
                        data={this.state.dataSource}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange= {(page, pageSize) => this.paginationChange(page, pageSize)}
                        rowSelection={rowSelection}
                    />

                </Card>
                
            </PageHeaderWrapper>
        )
    }
}

const WrappedAdvancedSearchForm = Form.create()(Management);

export default WrappedAdvancedSearchForm